package web_controller

import (
	"errors"
	"github.com/gin-gonic/gin"
	"os"
	"path"
	"strings"
	"transport/framework/fw_middleware"
	"transport/framework/fw_utils"
)

type imageController struct {
}

func (controller *imageController) UploadImg(c *gin.Context) {
	//获取图片文件
	img, err := c.FormFile("file")
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	httpPath := "/upload/" + fw_utils.GenXid() + path.Ext(img.Filename)
	err = c.SaveUploadedFile(img, "./"+httpPath)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	fw_utils.OK(c, httpPath, "ok")
}
func (controller *imageController) DeleteImg(c *gin.Context) {
	//获取图片文件
	url := c.Query("url")
	urlStrs := strings.Split(url, "/")
	lastStr := ""
	if len(urlStrs) <= 0 {
		fw_utils.Error(c, -1, errors.New("路径格式错误"), "")
		return
	}
	lastStr = urlStrs[len(urlStrs)-1]
	// http://127.0.0.1:8899/upload/%E8%90%A5%E4%B8%9A%E6%89%A7%E7%85%A7.jpg
	err := os.Remove("./upload/" + lastStr)
	if err != nil {
		fw_utils.Error(c, -1, err, "")
		return
	}
	fw_utils.OK(c, url, "ok")
}
func ImageRoute(r *gin.Engine) {
	controller := imageController{}
	v1 := r.Group("/oa").Use(fw_middleware.JwtAuthMiddleware())
	{
		v1.POST("/v1/file/upload", controller.UploadImg)
		v1.POST("/v1/file/delete", controller.DeleteImg)
	}
}
